package flysearch.core;

import java.io.File;
import java.io.FileReader;
import java.util.Date;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.analysis.standard.StandardAnalyzer;

public class Indexer{

    public var indexPath: String;
    public var dataPath: String; //建立索引的目录

    public function index() : Number{
        var index = new File(indexPath);
        var data = new File(dataPath);
        var start = new Date().getTime();
        //println("Start Time : {start}}");

        var writer = new IndexWriter(data, new StandardAnalyzer(), true);
        writer.setUseCompoundFile(false);
        indexDirectory(writer, index);

        var num = writer.docCount();

        writer.optimize();
        writer.close();

        var end = new Date().getTime();
        //println("Start Time : {end}}");

        return num;
    }

    function indexDoc(writer:IndexWriter, file:File) : Void{
        if(file.canRead()){
            var doc = new Document();
            doc.add(new Field("content", new FileReader(file)));
            doc.add(new Field("path",
                file.getCanonicalPath(),
                Field.Store.YES,
                Field.Index.NOT_ANALYZED));
            doc.add(new Field("modified",
                DateTools.timeToString(file.lastModified(), DateTools.Resolution.MINUTE),
                Field.Store.YES,
                Field.Index.NOT_ANALYZED));
            writer.addDocument(doc);
        }
    }

    function indexDirectory(writer: IndexWriter, dir: File) : Void{
        var files = dir.listFiles();
        for(file in files){
            if(file.isDirectory()){
                indexDirectory(writer, file);
            }else{
                indexDoc(writer, file);
            }
        }
    }
}


